/**
 * Created by zhouli on 18/3/8
 * Email li.zhou@huilianyi.com
 * 银行卡信息
 */
import React from 'react';
import {messages} from "share/common";
import 'styles/enterprise-manage/person-manage/person-detail/person-detail-components/bank-card.scss';
import PDService from 'containers/enterprise-manage/person-manage/person-detail/person-detail.service';
import Chooser from 'components/chooser';
import {
  Button, Switch, Modal, message,
  Icon, Input, Form, Checkbox, Select, Spin
} from 'antd';

const FormItem = Form.Item;
const Option = Select.Option;

class PersonBankCard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalKey: 0,//每次都需要变化，才能导致模态框每次渲染
      loading: false,
      data: [],
      showCreatModel: false,//弹窗是否显示
      card: {},//当前编辑或新增的银行卡
      cardTypeList: [],//银行卡类型的数组
    }
  }

  componentDidMount() {
    this.getCardTypes();
    this.setState({card: this.props.cardInfo});
  }

  componentWillReceiveProps(nextProps) {
    this.setState({card: nextProps.cardInfo});
  }

  //显示添加银行卡模态框
  showAddCardModel = () => {
    if(this.props.isReadOnly)return
    let {modalKey, card} = this.state;
    modalKey++;
    Object.assign(card,{
      contactBankAccountOID: null,
      bankAccountNo: null,
      bankAccountName: null,
      bankType: null,

      bankTypeBankCode: null,
      bankName: null,
      branchName: null,
      accountLocation: null,

      isPrimary: null,
      enable : true,
      bankCode : null,
      bankAccountType : null,
    });
    this.setState({
      modalKey,
      showCreatModel: true,
      card,//当前编辑或新增的银行卡
    })
  };
  // 编辑角色
  editCard = (e, record) => {
    let {modalKey} = this.state;
    modalKey++;
    this.setState({
      modalKey,
      showCreatModel: true,
    })
  };
  //去添加银行卡
  addCard = (e) => {
    e.preventDefault();
    let {card} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (!card.bankCode) {
          //请选择银行名称
          message.warning(messages("common.please.select") + messages('enterprise-manage.key215'/*银行名称*/));
          return;
        }
        card.bankAccountType = values.bankAccountType;
        if(!card.bankAccountType){
          card.bankAccountTypeName = "";
        }
        this.createUpdateCard(card);
      }
    })
  };
  cancelCard = () => {
    // 在这里重置一下，主要是为了清除模态框之前的状态，
    // 比如有校验字段，当取消再次弹窗的时候，校验提示还会显示出来
    this.props.form.resetFields();
    this.props.createCardOver();
    this.setState({
      showCreatModel: false,
    })
  };
  createUpdateCard = (card) => {
    this.setState({
      loading: true,
    });
    if (card.contactBankAccountOID) {
      PDService.updateBankCard(card)
        .then((res) => {
          this.props.createCardOver();
          this.setState({
            showCreatModel: false,
            loading: false,
          })
        })
        .catch((err) => {
          this.props.createCardOver();
        })
    } else {
      PDService.creatBankCard(card)
        .then((res) => {
          //当新增了卡片需要传到父组件，重新刷新组件
          this.props.createCardOver();
          this.setState({
            showCreatModel: false,
            loading: false,
          })
        })
        .catch((err) => {
          this.props.createCardOver();
        })
    }

  }
  //监听表单值
  handleFormChange = (e) => {
    if (this.state.loading) {
      this.setState({
        loading: false,
      })
    }
  };

  //银行开户名
  bankAccountNameChange = (e) => {
    let {card} = this.state;
    card.bankAccountName = e.target.value;
    this.setState({
      loading: false,
      card
    })
  }
  //银行账号
  bankAccountNoChange = (e) => {
    let {card} = this.state;
    card.bankAccountNo = e.target.value;
    this.setState({
      loading: false,
      card
    })
  }
  //开户地
  accountLocationChange = (e) => {
    let {card} = this.state;
    card.accountLocation = e.target.value;
    this.setState({
      loading: false,
      card
    })
  }
  //银行
  handleBankCodeChange = (e) => {
    let {card} = this.state;
    if (e.length > 0) {
      Object.assign(card,{
        bankCode: e[0].bankCode,
        branchName: e[0].bankBranchName,
        bankName: e[0].bankName,
        bankType: e[0].bankType,
        bankTypeBankCode: e[0].bankType + e[0].bankCode,
      })
    } else {
      Object.assign(card,{
        bankCode: '',
        branchName: '',
        bankName: '',
        bankType: '',
        bankTypeBankCode: '',
      });
    }
    this.setState({
      loading: false,
      card
    })
  }
  //状态
  switchCardStatusChange = (e) => {
    let {card} = this.state;
    card.enable = e;
    this.setState({
      loading: false,
      card
    })
  };

  // 是否默认
  handleCardDefaultChange = (e) => {
    let {card} = this.state;
    card.isPrimary = e.target.checked;
    this.setState({
      loading: false,
      card
    })
  };

  getCardTypes = () => {
    PDService.getCardTypes()
      .then((res) => {
        this.setState({
          cardTypeList: res.data ? res.data.values : [],
        });
      })
      .catch((err) => {
      })
  };

  renderCard(card) {
    const isReadOnly= this.props.isReadOnly
    if (this.props.isEmpty) {
      return (
        <div className={`card-add ${isReadOnly?'readonly':''}`}>
          <div className="card-add-icon-wrap" onClick={this.showAddCardModel}>
            <Icon type="plus" className="add-icon"/>
          </div>
        </div>
      )
    } else {
      let cardName = 'card';
      if (!card.enable) {
        cardName = 'disabled-card';
      }
      return (
        <div className={cardName}>
          <div className="card-top">
            <div className="f-left user-name">
              {card.bankAccountName}
            </div>
            <div className="f-right status">
              {card.enable ? messages('enterprise-manage.key216'/*启用中*/) : messages('enterprise-manage.key217'/*未启用*/)}
            </div>
            <div className="f-right is-default">
              {card.isPrimary ? messages('enterprise-manage.key218'/*默认*/) : ""}
            </div>
            <div className="clear"/>
          </div>

          <div className="card-number">
            {card.originalBankAccountNo}
          </div>

          <div className="card-middle1">
            <div className="f-left bank-title">
              {messages('enterprise-manage.key219'/*开户银行*/)}：
            </div>
            <div className="f-left bank-title-text">{card.branchName}</div>
            <div className="clear"/>
          </div>

          <div className="bank-card-position-middle">
            <div className="f-left bank-address">
              {messages('enterprise-manage.key220'/*开户地*/)}：
            </div>
            <div className="f-left bank-address-text">{card.accountLocation}</div>
            <div className="clear"/>
          </div>

          <div className="bank-card-position-middle">
            <div className="f-left bank-address"> {messages('enterprise-manage.key370')/*卡类型*/}：
            </div>
            <div className="f-left bank-address-text">{card.bankAccountTypeName}</div>
            <div className="clear"/>
          </div>

          <div className="card-bottom">
            {this.props.isShowEditBtn ? <div className="f-right bank-edit" onClick={this.editCard}>
              <Icon type="edit" className="info-circle"/>
              <span>
                  {messages("common.edit")}
              </span>
            </div> : <span/>}
            <div className="clear"/>
          </div>
        </div>
      )
    }
  }

  render() {
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 1},
    };
    const {card, loading, cardTypeList, showCreatModel, modalKey} = this.state;
    const {getFieldDecorator} = this.props.form;
    return (
      <div className="person-bank-card-wrap">
        {this.renderCard(card)}
        <Modal
          key={modalKey}
          closable
          width={600}
          className="create-update-modal person-bank-card-wrap-modal"
          title={card.contactBankAccountOID ? messages('enterprise-manage.key221'/*编辑银行卡信息*/) : messages('enterprise-manage.key222'/*新增银行卡信息*/)}
          visible={showCreatModel}
          footer={null}
          onCancel={this.cancelCard}
          destroyOnClose={true}
        >
          <Form onSubmit={this.addCard} onChange={this.handleFormChange}>
            <FormItem  {...formItemLayout} label={messages('enterprise-manage.key371')/*银行卡类型*/}>
              {getFieldDecorator('bankAccountType', {
                initialValue: card.bankAccountType
              })(
                <Select placeholder={messages('common.select')/*请选择*/} allowClear>
                  {cardTypeList.map(option => {
                    return <Option key={option.value}>{option.messageKey}</Option>
                  })}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout}
                      label={messages('enterprise-manage.key223'/*银行开户名*/)}
            >
              {getFieldDecorator('bankAccountName', {
                initialValue: card.bankAccountName,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.enter")
                  },
                  {
                    max: 30,
                    message: messages('enterprise-manage.key224'/*不能超过30个字符*/)
                  },
                  {
                    message:messages('enterprise-manage.key369')/*开户名只允许汉字、字母、斜杠、点、括号、空格*/,
                    validator: (rule, value, cb) => {
                      if (value === null || value === undefined || value === "") {
                        cb();
                        return;
                      }
                      // let regExp = /^[a-z\.\u4e00-\u9fa5\\\/]+$/i;
                      // \u2E80-\uFE4F 汉字包含生僻字
                      let regExp = /^(?!.*?[\u3000-\u303F\u4DC0-\u4DFF\u2800-\u28FF\u3200-\u32FF\u3300-\u33FF\u2700-\u27BF\u2600-\u26FF\uFE10-\uFE1F\uFE30-\uFE4F])[\u4e00-\u9fbb\u2E80-\uFE4Fa-zA-Z.()（）`·\\\/]+$/i;

                      //去掉空格
                      value = value.replace(/ /g, '');
                      if (value.length <= 30 && regExp.test(value)) {
                        cb();
                      } else {
                        cb(false);
                      }
                    },
                  },
                ],
              })(
                <div>
                  <Input onChange={this.bankAccountNameChange}
                         defaultValue={card.bankAccountName}
                         placeholder={messages("common.please.enter")}/>
                </div>
              )}
            </FormItem>
            <FormItem {...formItemLayout}
                      label={messages('enterprise-manage.key226'/*银行卡号*/)}
            >
              {getFieldDecorator('bankAccountNo', {
                initialValue: card.bankAccountNo,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.enter")
                  },
                  //任务编号 9661 银行账号校验必须包含数字
                  {
                    message: messages('enterprise-manage.key112'/*必须包含数字*/),
                    validator: (rule, value, cb) => {
                      if (value === null || value === undefined || value === "") {
                        cb();
                        return;
                      }
                      let regExp = /[0-9]/;
                      //去掉空格
                      value = value.replace(/ /g, '');
                      if (value.length <= 30 && regExp.test(value)) {
                        cb();
                      } else {
                        cb(false);
                      }
                    },
                  },
                  {
                    max: 30,
                    message: messages('enterprise-manage.key224'/*不能超过30个字符*/)
                  },
                ],
              })(
                <div>
                  <Input onChange={this.bankAccountNoChange}
                         defaultValue={card.bankAccountNo}
                         placeholder={messages("common.please.enter")}/>
                </div>
              )}
            </FormItem>
            <FormItem {...formItemLayout}
                      label={messages('enterprise-manage.key220'/*开户地*/)}
            >
              {getFieldDecorator('accountLocation', {
                initialValue: card.accountLocation,
                rules: [
                  {
                    max: 100,
                    message: messages('enterprise-manage.key227'/*不能超过100个字符*/)
                  },
                ],
              })(
                <div>
                  <Input onChange={this.accountLocationChange}
                         defaultValue={card.accountLocation}
                         placeholder={messages("common.please.enter")}/>
                </div>
              )}
            </FormItem>
            <FormItem {...formItemLayout}
                      label={
                        <span>
                           <span className="required-red">*&nbsp;</span>
                           <span>{messages('enterprise-manage.key215'/*银行名称*/)}</span>
                        </span>
                      }
            >
              <Chooser single={true}
                       type="select_bank"
                       value={card.bankCode ? [
                         {
                           bankBranchName: card.branchName,
                           bankCode: card.bankCode,
                           bankName: card.bankName,
                           bankType: card.bankType,
                           bankTypeBankCode: card.bankType + card.bankCode
                         }
                       ] : []}
                       placeholder={messages("common.please.select")}
                       labelKey="bankBranchName"
                       onChange={this.handleBankCodeChange}
                       valueKey="bankTypeBankCode"
                       listExtraParams={{}}/>
            </FormItem>
            {/*状态*/}
            <FormItem {...formItemLayout}
                      label={messages("common.column.status")} colon={true}>
              {getFieldDecorator('enable', {
                initialValue: card.enable
              })(
                <div>
                  <Switch
                    defaultChecked={card.enable}
                    checked={card.enable}
                    checkedChildren={<Icon type="check"/>}
                    unCheckedChildren={<Icon type="cross"/>}
                    onChange={this.switchCardStatusChange}/>
                  <span className="enabled-type" style={{
                    marginLeft: 20,
                    width: 100
                  }}>{card.enable ? messages("common.status.enable") : messages("common.disabled")}</span>
                </div>)}
            </FormItem>

            <FormItem {...formItemLayout}
                      label={messages('enterprise-manage.key228'/*设为默认*/)}
            >
              {getFieldDecorator('isPrimary', {
                initialValue: card.isPrimary
              })(
                <div>
                  <Checkbox defaultChecked={card.isPrimary}
                            checked={card.isPrimary}
                            onChange={this.handleCardDefaultChange}
                  >
                    {messages('enterprise-manage.key229'/*是（只能有一个默认）*/)}
                  </Checkbox>
                </div>)}
            </FormItem>


            <div className="role-list-from-footer">
              <Button onClick={this.cancelCard}>
                {messages("common.cancel")}
              </Button>
              &nbsp;&nbsp;&nbsp;
              <Button type="primary" htmlType="submit" disabled={loading}>
                {messages("common.save")}
              </Button>
            </div>
          </Form>

        </Modal>
      </div>
    )
  }
}

PersonBankCard.contextTypes = {
  router: React.PropTypes.object
};
PersonBankCard.propTypes = {
  createCardOver: React.PropTypes.func,//创建银行卡后
  cardInfo: React.PropTypes.object,//银行卡对象
  isEmpty: React.PropTypes.bool,// 是否是空的
  disabled: React.PropTypes.bool,// 是否是启用的
  isShowEditBtn: React.PropTypes.bool,// 是否显示编辑按钮
  isReadOnly:  React.PropTypes.bool,// 是否是只读
};
PersonBankCard.defaultProps = {
  isShowEditBtn: true
};
const WrappedPersonBankCard = Form.create()(PersonBankCard);
export default WrappedPersonBankCard;
